/**
 * 主题 Redux Actions
 */

import { 
  THEME_LOAD_START,
  THEME_LOAD_SUCCESS,
  THEME_LOAD_FAILURE,
  THEME_SET_CONFIG,
  THEME_UPDATE_CONFIG,
  THEME_RESET,
  THEME_CLEAR_ERROR,
} from './reduxType';
import { getThemeSettings, clearThemeCache } from '@/service/theme';
import { applyThemeWithTransition, sanitizeThemeConfig } from '@/utils/themeHelper';

/**
 * 加载主题配置
 */
export const loadThemeConfig = (forceRefresh = false) => {
  return async (dispatch) => {
    dispatch({ type: THEME_LOAD_START });
    
    try {
      console.log('[ThemeAction] 开始加载主题配置...');
      const themeConfig = await getThemeSettings(forceRefresh);
      
      console.log('[ThemeAction] 获取到的配置:', themeConfig);
      console.log('[ThemeAction] 主背景色:', themeConfig.theme_bg_primary);
      
      // 验证和清理主题配置
      const sanitized = sanitizeThemeConfig(themeConfig);
      
      console.log('[ThemeAction] 清理后的配置:', sanitized);
      console.log('[ThemeAction] 清理后主背景色:', sanitized.theme_bg_primary);
      
      // 应用主题配置
      console.log('[ThemeAction] 开始应用主题到DOM...');
      const applyResult = await applyThemeWithTransition(sanitized);
      console.log('[ThemeAction] 应用结果:', applyResult);
      
      // 验证应用效果
      const currentBg = getComputedStyle(document.documentElement).getPropertyValue('--theme-bg-primary').trim();
      console.log('[ThemeAction] 应用后CSS变量值:', currentBg);
      
      if (currentBg !== sanitized.theme_bg_primary) {
        console.error('[ThemeAction] ⚠️ CSS变量未正确应用！');
        console.error('[ThemeAction] 预期:', sanitized.theme_bg_primary);
        console.error('[ThemeAction] 实际:', currentBg);
      }
      
      dispatch({
        type: THEME_LOAD_SUCCESS,
        payload: {
          config: sanitized,
          timestamp: Date.now(),
        },
      });
      
      console.log('[ThemeAction] 主题配置加载成功');
    } catch (error) {
      console.error('[ThemeAction] 加载主题配置失败:', error);
      console.error('[ThemeAction] 错误堆栈:', error.stack);
      dispatch({
        type: THEME_LOAD_FAILURE,
        payload: error.message || '加载主题配置失败',
      });
    }
  };
};

/**
 * 刷新主题配置（清除缓存并重新加载）
 */
export const refreshThemeConfig = () => {
  return async (dispatch) => {
    console.log('[ThemeAction] 刷新主题配置...');
    clearThemeCache();
    return dispatch(loadThemeConfig(true));
  };
};

/**
 * 直接设置主题配置（同时应用到DOM）
 */
export const setThemeConfig = (config) => {
  return async (dispatch) => {
    try {
      console.log('[ThemeAction] 设置主题配置...');
      
      // 验证和清理配置
      const sanitized = sanitizeThemeConfig(config);
      
      // 立即应用到DOM
      await applyThemeWithTransition(sanitized);
      
      // 更新Redux状态
      dispatch({
        type: THEME_SET_CONFIG,
        payload: sanitized,
      });
      
      console.log('[ThemeAction] 主题配置已设置并应用');
    } catch (error) {
      console.error('[ThemeAction] 设置主题配置失败:', error);
    }
  };
};

/**
 * 更新部分主题配置（同时应用到DOM）
 */
export const updateThemeConfig = (updates) => {
  return async (dispatch, getState) => {
    try {
      console.log('[ThemeAction] 更新主题配置...');
      
      // 获取当前配置
      const currentConfig = getState().theme.config || {};
      
      // 合并配置
      const newConfig = { ...currentConfig, ...updates };
      
      // 验证和清理
      const sanitized = sanitizeThemeConfig(newConfig);
      
      // 应用到DOM
      await applyThemeWithTransition(sanitized);
      
      // 更新Redux状态
      dispatch({
        type: THEME_UPDATE_CONFIG,
        payload: sanitized,
      });
      
      console.log('[ThemeAction] 主题配置已更新并应用');
    } catch (error) {
      console.error('[ThemeAction] 更新主题配置失败:', error);
    }
  };
};

/**
 * 重置主题配置
 */
export const resetThemeConfig = () => {
  return {
    type: THEME_RESET,
  };
};

/**
 * 清除错误信息
 */
export const clearThemeError = () => {
  return {
    type: THEME_CLEAR_ERROR,
  };
};

